﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using T2V.SharePoint.Common.Utilities;

namespace PepsiCo.Intranet.WebParts.DocumentLibraryTreeView
{
    public partial class DocumentLibraryTreeViewUserControl : UserControl
    {
        string documentLibrary = string.Empty;
        string documentLibraryFolderPath = string.Empty;
        bool IsCurrentLoginUser;
        bool IsOnlyFoldersNeedShow;
        string _strCurrentUser = string.Empty;
        SPSite spSite = SPContext.Current.Site;
        SPWeb spWeb;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Retriving the document library name from the custom web part property //
                RetrieveDocLibName();
            }
        }
        #region -- CUSTOM METHODS --

        private void RetrieveDocLibName()
        {
            try
            {
                DocumentLibraryTreeView parent = (DocumentLibraryTreeView)this.Parent;
                if (documentLibrary != null && !string.IsNullOrEmpty(parent.DocumentLibrary.Trim()))
                {
                    documentLibrary = parent.DocumentLibrary.Trim();
                    documentLibraryFolderPath = parent.DocumentLibraryFolderPath != null ? parent.DocumentLibraryFolderPath.Trim() : string.Empty;
                    IsCurrentLoginUser = parent._IsLoginUser;
                    IsOnlyFoldersNeedShow = parent._IsOnlyFolders;
                    SPSite site = SPContext.Current.Site;
                    spWeb = site.OpenWeb();
                    tvDocumentLibrary.Nodes.Clear();

                    // Creating an object of the document library //
                    SPDocumentLibrary spDocumentLibrary;
                    try
                    {
                        spDocumentLibrary = (SPDocumentLibrary)spWeb.Lists[documentLibrary.Trim()];
                    }
                    catch
                    {
                        spDocumentLibrary = (SPDocumentLibrary)Utility.GetListFromURL("/" + documentLibrary, spWeb);
                    }

                    // Creating an object of the root folder of the document library //
                    SPFolder spFolder = spDocumentLibrary.RootFolder;

                    // Creating the parent node of the tree view //
                    //TreeNode treeNodeRoot = new TreeNode(spFolder.Name.Trim(), spFolder.Name.Trim(), @"/_layouts/images/folder.gif", spFolder.ServerRelativeUrl.Trim(), "_blank");
                    TreeNode treeNodeRoot = new TreeNode(spDocumentLibrary.Title, spFolder.Name.Trim(), @"/_layouts/images/itdl.png");

                    //specify the Folder level
                    SPFolder spSpecyfiedFolder = spDocumentLibrary.ParentWeb.GetFolder(spFolder.Url + "/" + documentLibraryFolderPath.TrimStart('/'));

                    // Calling the custom method to get all the folders //
                    GetAllFilesFolders(spSpecyfiedFolder, treeNodeRoot, IsCurrentLoginUser, IsOnlyFoldersNeedShow);

                    // Adding the tree nodes to the tree view control //
                    tvDocumentLibrary.Nodes.Add(treeNodeRoot);
                }
                else
                {
                    lbl.Text = "Please mention a document library.";
                }
            }
            catch (Exception ex)
            {
                lbl.Text = "There is an error occured. Please check if you specify a valid Document Library Name.";
            }

        }

        /// <summary>
        /// This custom menthod is used to get all the files and folders
        /// </summary>
        /// <param name="spFolder"></param>
        /// <param name="parentNode"></param>
        protected void GetAllFilesFolders(SPFolder spFolder, TreeNode parentNode, bool IsCheckCurrentUser, bool IsOnlyFoldersNeedShow)
        {
            SPQuery spQuery = new SPQuery();
            spQuery.Folder = spFolder;
            string strCurrentUserName = spWeb.CurrentUser.Name.ToString();
            if (IsOnlyFoldersNeedShow != true)
            {
                if (IsCheckCurrentUser == true)
                {
                    spQuery.Query = "<Where><Eq><FieldRef Name='Author' /><Value Type='User'>" + strCurrentUserName.ToString() + "</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";
                    SPListItemCollection spListItemCollection = spWeb.Lists[spFolder.ParentListId].GetItems(spQuery);

                    foreach (SPListItem spListItem in spListItemCollection)
                    {
                        // Checking whether the item is a file or a folder //
                        if (spListItem.Folder != null)
                        {
                            SPSite site = SPContext.Current.Site;
                            spWeb = site.OpenWeb();

                            // Creating the node for the folder //
                            //TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif", spListItem.Folder.ServerRelativeUrl.Trim(), "_blank");
                            TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif");
                            parentNode.ChildNodes.Add(treeNodeChildFolder);

                            // Calling the custom method to get all the subfolder and files within the folder //
                            GetAllFilesFolders(spListItem.Folder, treeNodeChildFolder, true, false);
                        }
                        else
                        {
                            // Creating and object of the file //
                            SPFile spFile = spListItem.File;

                            // Setting the display URL of the file //
                            //string displayURL = SPContext.Current.Site.Url.Trim() + @"/" + spFile.Url.Trim();
                            string displayURL = spWeb.Url.Trim() + @"/" + spFile.Url.Trim();
                            // Setting the icon URL of the file //
                            string iconURL = spFile.IconUrl.Trim();
                            int y = iconURL.LastIndexOf("/") + 1;
                            iconURL = @"/_layouts/images/" + iconURL.Substring(y, iconURL.Length - y);

                            // Creating the node of the file //
                            TreeNode treeNodeChildFile = new TreeNode(spFile.Name.Trim(), spFile.Name.Trim(), iconURL.Trim(), displayURL.Trim(), "_blank");
                            parentNode.ChildNodes.Add(treeNodeChildFile);
                        }
                    }
                }
                else
                {
                    SPListItemCollection spListItemCollection = spWeb.Lists[spFolder.ParentListId].GetItems(spQuery);

                    foreach (SPListItem spListItem in spListItemCollection)
                    {
                        // Checking whether the item is a file or a folder //
                        if (spListItem.Folder != null)
                        {
                            // Creating the node for the folder //
                            //TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif", spListItem.Folder.ServerRelativeUrl.Trim(), "_blank");
                            TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif");
                            parentNode.ChildNodes.Add(treeNodeChildFolder);

                            // Calling the custom method to get all the subfolder and files within the folder //
                            GetAllFilesFolders(spListItem.Folder, treeNodeChildFolder, false, false);
                        }
                        else
                        {
                            // Creating and object of the file //
                            SPFile spFile = spListItem.File;

                            // Setting the display URL of the file //
                            string displayURL = spWeb.Url.Trim() + @"/" + spFile.Url.Trim();

                            // Setting the icon URL of the file //
                            string iconURL = spFile.IconUrl.Trim();
                            int y = iconURL.LastIndexOf("/") + 1;
                            iconURL = @"/_layouts/images/" + iconURL.Substring(y, iconURL.Length - y);

                            // Creating the node of the file //
                            TreeNode treeNodeChildFile = new TreeNode(spFile.Name.Trim(), spFile.Name.Trim(), iconURL.Trim(), displayURL.Trim(), "_blank");
                            parentNode.ChildNodes.Add(treeNodeChildFile);
                        }
                    }
                }
            }
            else // This section will be show only folder view...
            {
                if (IsCheckCurrentUser == true)
                {
                    spQuery.Query = "<Where><Eq><FieldRef Name='Author' /><Value Type='User'>" + strCurrentUserName.ToString() + "</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";
                    SPListItemCollection spListItemCollection = spWeb.Lists[spFolder.ParentListId].GetItems(spQuery);

                    foreach (SPListItem spListItem in spListItemCollection)
                    {
                        // Checking whether the item is a file or a folder //
                        if (spListItem.Folder != null)
                        {
                            SPSite site = SPContext.Current.Site;
                            spWeb = site.OpenWeb();

                            // Creating the node for the folder //
                            //TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif", spListItem.Folder.ServerRelativeUrl.Trim(), "_blank");
                            TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif");
                            parentNode.ChildNodes.Add(treeNodeChildFolder);

                            // Calling the custom method to get all the subfolder and files within the folder //
                            GetAllFilesFolders(spListItem.Folder, treeNodeChildFolder, true, false);
                        }

                    }
                }
                else
                {
                    SPListItemCollection spListItemCollection = spWeb.Lists[spFolder.ParentListId].GetItems(spQuery);

                    foreach (SPListItem spListItem in spListItemCollection)
                    {
                        // Checking whether the item is a file or a folder //
                        if (spListItem.Folder != null)
                        {
                            // Creating the node for the folder //
                            //TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif", spListItem.Folder.ServerRelativeUrl.Trim(), "_blank");
                            TreeNode treeNodeChildFolder = new TreeNode(spListItem.Folder.Name.Trim(), Convert.ToString(spListItem.ID).Trim(), @"/_layouts/images/folder.gif");
                            parentNode.ChildNodes.Add(treeNodeChildFolder);

                            // Calling the custom method to get all the subfolder and files within the folder //
                            GetAllFilesFolders(spListItem.Folder, treeNodeChildFolder, false, true);
                        }
                    }
                }
            }
        }
        #endregion
    }
}
